<template>
  <Form ref="formRef" :model="formParams">
    <Row>
      <Col span="5">
        <FormItem label="结算日期" :label-width="100">
          <RadioGroup v-model="chooseDate" type="button" @change="changeDate" button-style="solid">
            <Radio label="年"></Radio>
            <Radio label="半年"></Radio>
            <Radio label="季度"></Radio>
            <Radio label="月"></Radio>
          </RadioGroup>
        </FormItem>
      </Col>
      <Col span="6">
        <FormItem :label-width="50">
          <el-date-picker
            v-if="chooseDate === '年'"
            v-model="settlementDate"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="year"
            placeholder="选择年"
          />
          <HalfYearPicker
            v-model="settlementDate"
            :placeholder="'选择半年'"
            v-if="chooseDate === '半年'"
          />
          <QuarterPicker
            v-model="settlementDate"
            :placeholder="'选择季度'"
            v-if="chooseDate === '季度'"
          />

          <el-date-picker
            v-if="chooseDate === '月'"
            v-model="settlementDate"
            type="month"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择月"
          />
        </FormItem>
      </Col>
      <Col span="4">
        <FormItem label="医疗机构" prop="areaID">
          <Select v-model="formParams.areaID" style="width: 200px" @on-change="areaChg">
            <Option v-for="item in area" :value="item.areaID" :key="item.areaID">{{
              item.name
            }}</Option>
          </Select>
        </FormItem>
      </Col>
      <Col span="4">
        <FormItem label="科室" prop="categoryID">
          <TreeSelect
            :data="treeList.data"
            @on-change="treeChg"
            v-model="formParams.categoryID"
            multiple
            style="width: 200px"
          >
          </TreeSelect>
        </FormItem>
      </Col>
      <Col span="4">
        <Space style="margin-left: 20px">
          <Button type="primary" icon="md-search" @click="goSearch">查询</Button>
          <Button type="dashed" icon="md-refresh" @click="clear">重置</Button>
        </Space>
      </Col>
    </Row>
  </Form>
  <Row gutter="20" align="middle">
    <Col span="3">
      <Card>
        <div style="text-align: center">
          <Tag size="large" color="green">住院患者总数</Tag>
          <div></div>
          <CountUp :end="userInfo.total" :duration="2" ref="count" v-font="24" />
          <br />
          <Text italic>近30天</Text>&nbsp;
          <Trend flag="up" text-color> 12.5%</Trend>
        </div>
      </Card>
    </Col>
    <Col span="3">
      <Card>
        <div style="text-align: center">
          <Tag size="large" color="cyan">已提交病案数</Tag>
          <div></div>
          <CountUp :end="userInfo.end" :duration="2" ref="count" v-font="24" />
          <Progress
            :percent="45"
            :stroke-width="20"
            status="active"
            text-inside
            :stroke-color="['#13C2C2', '#13C2C2']"
          />
        </div>
      </Card>
    </Col>
    <Col span="3">
      <Card>
        <div style="text-align: center">
          <Tag size="large" color="blue">已生成清单数</Tag>
          <div></div>
          <CountUp :end="userInfo.ysc" :duration="2" ref="count" v-font="24" />
          <Progress
            :percent="45"
            :stroke-width="20"
            status="active"
            text-inside
            :stroke-color="['#1890FF', '#1890FF']"
          />
        </div>
      </Card>
    </Col>
    <Col span="3">
      <Card>
        <div style="text-align: center">
          <Tag size="large" color="geekblue">非编码缺陷清单数</Tag>
          <div></div>
          <CountUp :end="userInfo.fbmqx" :duration="2" ref="count" v-font="24" />
          <Progress
            :percent="45"
            :stroke-width="20"
            status="active"
            text-inside
            :stroke-color="['#2F54EB', '#2F54EB']"
          />
        </div>
      </Card>
    </Col>
    <Col span="3">
      <Card>
        <div style="text-align: center">
          <Tag size="large" color="purple">编码缺陷清单数</Tag>
          <div></div>
          <CountUp :end="userInfo.bmqx" :duration="2" ref="count" v-font="24" />
          <Progress
            :percent="45"
            :stroke-width="20"
            status="active"
            text-inside
            :stroke-color="['#722ED1', '#722ED1']"
          />
        </div>
      </Card>
    </Col>
    <Col span="3">
      <Card>
        <div style="text-align: center">
          <Tag size="large" color="magenta">已入组清单数</Tag>
          <div></div>
          <CountUp :end="userInfo.yrz" :duration="2" ref="count" v-font="24" />
          <Progress
            :percent="80"
            :stroke-width="20"
            status="active"
            text-inside
            :stroke-color="['#EB2F96', '#EB2F96']"
          />
        </div>
      </Card>
    </Col>
    <Col span="3">
      <Card>
        <div style="text-align: center">
          <Tag size="large" color="#17B81D">已审核清单数</Tag>
          <div></div>
          <CountUp :end="userInfo.ysh" :duration="2" ref="count" v-font="24" />
          <Progress
            :percent="45"
            :stroke-width="20"
            status="active"
            text-inside
            :stroke-color="['#17B81D', '#17B81D']"
          />
        </div>
      </Card>
    </Col>
    <Col span="3">
      <Card>
        <div style="text-align: center">
          <Tag size="large" color="#D24DC3">已上传清单数</Tag>
          <div></div>
          <CountUp :end="userInfo.ysh1" :duration="2" ref="count" v-font="24" />
          <Progress
            :percent="45"
            :stroke-width="20"
            status="active"
            text-inside
            :stroke-color="['#D24DC3', '#D24DC3']"
          />
        </div>
      </Card>
    </Col>
  </Row>
  <Row style="padding-top: 30px">
    <Col span="12">
      <div style="width: 90%; height: 350px" id="line1"></div>
    </Col>
    <Col span="12">
      <div style="width: 90%; height: 350px" id="line2"></div>
    </Col>
  </Row>
  <Row style="padding-top: 10px">
    <Col span="12">
      <Divider>
        <Tag size="large" color="purple">编码缺陷分析TOP10</Tag>
      </Divider>
      <Table highlight-row :columns="columns" :data="data1"></Table>
    </Col>
    <Col span="12">
      <Divider>
        <Tag size="large" color="geekblue">非编码缺陷分析TOP10</Tag>
      </Divider>
      <Table highlight-row :columns="columns" :data="data2"></Table>
    </Col>
  </Row>
</template>
<script setup>
import * as echarts from 'echarts'
import { onActivated, onMounted, onBeforeUnmount } from 'vue'
import HalfYearPicker from '../../../components/common/HalfYearPicker.vue'
import QuarterPicker from '../../../components/common/QuarterPicker.vue'

import moment from 'moment'
import http from '@/util/http1'
const chooseDate = ref('年')
let formParams = ref({
  startSettleDate: '',
  endSettleDate: '',
  areaID: '',
  categoryID: [],
})

const area = ref([])
const initArea = () => {
  http.get('/Basic/Area/ListByUser', {}).then((response) => {
    area.value = response.data
  })
}
initArea()

const areaChg = (areaID) => {
  formParams.areaID = areaID
  initTreeList()
}

let treeList = reactive({ data: [] })
const initTreeList = () => {
  http.get('/Basic/Category/TreeList?areaID=' + formParams.areaID, {}).then((response) => {
    treeList.data = formatTreeData(response.data)
  })
}

const formatTreeData = (data) => {
  return data.map((item) => ({
    title: item.title,
    value: item.categoryID,
    expand: true,
    children: item.children ? formatTreeData(item.children) : null,
  }))
}

const userInfo = ref({
  total: 0,
  end: 0,
  ysc: 0,
  fbmqx: 0,
  bmqx: 0,
  yrz: 0,
  ysh: 0,
  ysh1: 0,
})

const treeChg = (value) => {
  console.log(value)
}

const settlementDate = ref('')
let lineChart1 = null
let lineChart2 = null

const initLine1 = () => {
  const line1 = document.getElementById('line1')
  lineChart1 = echarts.init(line1)
  updateLine1Chart()
}

const updateLine1Chart = () => {
  if (!lineChart1) return

  const option1 = {
    title: {
      text: '患者总数、已提交病案数、已生成清单数趋势图',
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      left: 500,
      data: lineList1.value.legend || [],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: lineList1.value.xAxis || [],
    },
    yAxis: {
      type: 'value',
    },
    series: lineList1.value.series || [],
  }
  lineChart1.setOption(option1)
}

onMounted(() => {
  initLine1()
})

const initLine2 = () => {
  const line2 = document.getElementById('line2')
  lineChart2 = echarts.init(line2)
  updateLine2Chart()
}

const updateLine2Chart = () => {
  if (!lineChart2) return

  const option2 = {
    title: {
      text: '已生成清单数、入组清单数、编码缺陷数趋势图',
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      left: 500,
      data: lineList2.value.legend || [],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: lineList2.value.xAxis || [],
    },
    yAxis: {
      type: 'value',
    },
    series: lineList2.value.series || [],
  }
  lineChart2.setOption(option2)
}

onMounted(() => {
  initLine2()
})

const columns = [
  {
    title: '序号',
    type: 'index',
    align: 'center',
  },
  {
    title: '原因',
    key: 'label',
    align: 'center',
  },
  {
    title: '个数',
    key: 'value',
    align: 'center',
  },
]

const changeDate = (val) => {
  settlementDate.value = ''
}
const formRef = ref(null)
const clear = () => {
  chooseDate.value = '年'
  settlementDate.value = ''
  formRef.value.resetFields()
}
const lineList1 = ref({
  legend: [],
  xAxis: [],
  series: [],
})
const lineList2 = ref({
  legend: [],
  xAxis: [],
  series: [],
})
const data1 = ref([])
const data2 = ref([])
const goSearch = () => {
  if (settlementDate.value) {
    if (chooseDate.value === '年') {
      formParams.value.startSettleDate = moment(settlementDate.value)
        .startOf('year')
        .format('YYYY-MM-DD HH:mm:ss')
      formParams.value.endSettleDate = moment(settlementDate.value)
        .endOf('year')
        .format('YYYY-MM-DD HH:mm:ss')
    } else if (chooseDate.value === '半年') {
      const [year, half] = settlementDate.value.split('-')
      if (half === '1') {
        formParams.value.startSettleDate = moment(`${year}-01-01`).format('YYYY-MM-DD HH:mm:ss')
        formParams.value.endSettleDate = moment(`${year}-06-30`).format('YYYY-MM-DD 23:59:59')
      } else if (half === '2') {
        formParams.value.startSettleDate = moment(`${year}-07-01`).format('YYYY-MM-DD HH:mm:ss')
        formParams.value.endSettleDate = moment(`${year}-12-31`).format('YYYY-MM-DD 23:59:59')
      }
    } else if (chooseDate.value === '季度') {
      const [year, quarter] = settlementDate.value.split('-')
      const quarterMap = {
        '01': { start: '01-01', end: '03-31' },
        '02': { start: '04-01', end: '06-30' },
        '03': { start: '07-01', end: '09-30' },
        '04': { start: '10-01', end: '12-31' },
      }
      const { start, end } = quarterMap[quarter]
      formParams.value.startSettleDate = moment(`${year}-${start}`).format('YYYY-MM-DD 00:00:00')
      formParams.value.endSettleDate = moment(`${year}-${end}`).format('YYYY-MM-DD 23:59:59')
    } else if (chooseDate.value === '月') {
      formParams.value.startSettleDate = moment(settlementDate.value)
        .startOf('month')
        .format('YYYY-MM-DD HH:mm:ss')
      formParams.value.endSettleDate = moment(settlementDate.value)
        .endOf('month')
        .format('YYYY-MM-DD HH:mm:ss')
    }
  } else {
    formParams.value.startSettleDate = formParams.value.endSettleDate = ''
  }

  const params = Object.assign({}, formParams.value)

  http.post('/Settlement/List/Overview', params).then((res) => {
    console.log(res)
    Object.assign(userInfo, res.data)
    lineList1.value = res.data.line1 || { legend: [], xAxis: [], series: [] }
    lineList2.value = res.data.line2 || { legend: [], xAxis: [], series: [] }
    data1.value = res.data.top1 || []
    data2.value = res.data.top2 || []
    updateLine1Chart()
    updateLine2Chart()
  })
}
onActivated(() => {
  goSearch()
})

window.addEventListener('resize', () => {
  lineChart1?.resize()
  lineChart2?.resize()
})

onBeforeUnmount(() => {
  lineChart1?.dispose()
  lineChart2?.dispose()
})
</script>

<style>
.el-date-range-picker {
  width: 680px !important;
}
.el-date-range-picker .el-picker-panel__body {
  min-width: 640px;
}

.custom-year-cell {
  padding: 4px;
  text-align: center;
}

.cell-buttons {
  display: flex;
  gap: 4px;
  justify-content: center;
  margin-top: 4px;
}

.cell-buttons .el-button {
  flex: 1;
  min-width: 60px;
}

/* 调整日期选择器的宽度以适应按钮 */
.el-picker-panel {
  min-width: 200px !important;
}

.half-year-cell {
  padding: 8px 0;
  text-align: center;
}

.year-text {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.half-year-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
}

.half-year-buttons .el-button {
  flex: 1;
  margin: 0;
  padding: 4px 0;
}

.half-year-buttons .divider {
  width: 1px;
  height: 16px;
  background-color: #dcdfe6;
  margin: 0 4px;
}

.half-year-buttons .active {
  color: var(--el-color-primary);
  font-weight: bold;
}

/* 调整日期选择器的宽度 */
.el-picker-panel.el-date-picker {
  min-width: 280px !important;
}

.el-year-table td {
  padding: 8px 0;
}
</style>
